package com.jobsleaf.viewsorter.tree;

import java.util.Comparator;

import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;

public class TreeSorter extends ViewerSorter
{
	public int compare(Viewer viewer, Object e1, Object e2)
	{
		int cat1 = category(e1);
		int cat2 = category(e2);
		if (cat1 != cat2)
			return cat1 - cat2;
		String name1, name2;
		if (viewer == null || !(viewer instanceof ContentViewer))
		{
			name1 = e1.toString();
			name2 = e2.toString();
		} else
		{
			IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
			if (prov instanceof ILabelProvider)
			{
				ILabelProvider lprov = (ILabelProvider) prov;
				name1 = lprov.getText(e1);
				name2 = lprov.getText(e2);
			} else
			{
				name1 = e1.toString();
				name2 = e2.toString();
			}
		}
		if (name1 == null)
			name1 = "";
		if (name2 == null)
			name2 = "";
		name1 = splitString(name1);
		name2 = splitString(name2);

		return comparator.compare(name1, name2);
	}

	protected String splitString(String name)
	{
		String test = "";
		try
		{
			test = name.toLowerCase().substring(name.indexOf("=") + 1);
		} 
		catch (Exception e)
		{
			test = name;
		}
		return test.trim();
	}

	private Comparator<Object> comparator = new Comparator<Object>()
	{
		@Override
		public int compare(Object o1, Object o2)
		{
			int state = -1;
			try
			{
				int a = Integer.parseInt((String) o1);
				int b = Integer.parseInt((String) o2);
				state = a > b? 1 : 0;
			}
			catch (Exception e)
			{
				state = ((String) o1).compareToIgnoreCase(((String) o2));
			}
			return state;
		}
	};
}
